package com.jason.item.controller;

import com.jason.common.vo.CommonReturnType;
import com.jason.item.controller.vo.ItemVO;
import com.jason.item.model.ItemModel;
import com.jason.item.service.ItemService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.List;
import java.util.stream.Collectors;

@Slf4j
@RestController
@CrossOrigin(allowCredentials = "true", allowedHeaders = "*" , methods = {RequestMethod.GET, RequestMethod.POST, RequestMethod.DELETE, RequestMethod.PUT})
@RequestMapping("/item")
public class ItemController {

    @Autowired
    private ItemService itemService;

    @PostMapping("/creator")
    public CommonReturnType createItem(@Valid ItemModel itemModel){

            ItemModel item = itemService.createItem(itemModel);
        ItemVO itemVO = ItemVO.convertByItemModel(item);
        return CommonReturnType.builder(itemVO);
    }
    @GetMapping("/{id}")
    public CommonReturnType getItemDetail(@PathVariable("id") Integer id){

        ItemModel item = itemService.getItemById(id);
        ItemVO itemVO = ItemVO.convertByItemModel(item);
        return CommonReturnType.builder(itemVO);
    }


    @GetMapping("/list")
    public CommonReturnType listItem(){

        List<ItemModel> itemModelList = itemService.listItem();
        List<ItemVO> itemVOList = itemModelList.stream().map(itemModel -> {
            ItemVO itemVO = ItemVO.convertByItemModel(itemModel);
            return itemVO;
        }).collect(Collectors.toList());
        return CommonReturnType.builder(itemVOList);
    }
}
